package com.laowang.project.system.service.impl;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;

import com.laowang.common.exception.CustomException;
import com.laowang.common.utils.DateUtil;
import com.laowang.common.utils.IdWorker;
import com.laowang.common.utils.PayUtil;
import com.laowang.common.utils.SecurityUtils;
import com.laowang.framework.redis.RedisCache;
import com.laowang.framework.web.domain.AjaxResult;
import com.laowang.project.pay.config.MyWxPayConfigUtil;
import com.laowang.project.system.domain.*;
import com.laowang.project.system.mapper.WxOrderMapper;
import com.laowang.project.system.service.*;
import io.swagger.models.auth.In;
import org.omg.CORBA.PRIVATE_MEMBER;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.laowang.project.system.mapper.MyGoodsBuyMapper;
import org.springframework.transaction.annotation.Transactional;
import oshi.jna.platform.mac.SystemB;

/**
 * 商品购买Service业务层处理
 *
 * @author laowang
 * @date 2023-07-21
 */
@Service
public class MyGoodsBuyServiceImpl implements MyGoodsBuyService {
    @Autowired
    private MyGoodsBuyMapper myGoodsBuyMapper;

    @Autowired
    private MyGoodsService myGoodsService;

    @Autowired
    private WxUserService wxUserService;

    @Autowired
    private IdWorker idWorker;

    @Autowired
    private WxOrderMapper wxOrderMapper;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private UserGoldLogService userGoldLogService;

    @Autowired
    private UserPointLogService userPointLogService;

    @Autowired
    private MyGoodsCatService myGoodsCatService;

    /**
     * 查询商品购买
     *
     * @param id 商品购买ID
     * @return 商品购买
     */
    @Override
    public MyGoodsBuy selectMyGoodsBuyById(Integer id) {
        return myGoodsBuyMapper.selectMyGoodsBuyById(id);
    }

    /**
     * 查询商品购买列表
     *
     * @param myGoodsBuy 商品购买
     * @return 商品购买
     */
    @Override
    public List<MyGoodsBuy> selectMyGoodsBuyList(MyGoodsBuy myGoodsBuy) {
        return myGoodsBuyMapper.selectMyGoodsBuyList(myGoodsBuy);
    }

    /**
     * 新增商品购买
     *
     * @param myGoodsBuy 商品购买
     * @return 结果
     */
    @Override
    public int insertMyGoodsBuy(MyGoodsBuy myGoodsBuy) {
        return myGoodsBuyMapper.insertMyGoodsBuy(myGoodsBuy);
    }

    /**
     * 修改商品购买
     *
     * @param myGoodsBuy 商品购买
     * @return 结果
     */
    @Override
    public int updateMyGoodsBuy(MyGoodsBuy myGoodsBuy) {
        return myGoodsBuyMapper.updateMyGoodsBuy(myGoodsBuy);
    }

    /**
     * 批量删除商品购买
     *
     * @param ids 需要删除的商品购买ID
     * @return 结果
     */
    @Override
    public int deleteMyGoodsBuyByIds(Integer[] ids) {
        return myGoodsBuyMapper.deleteMyGoodsBuyByIds(ids);
    }

    /**
     * 删除商品购买信息
     *
     * @param id 商品购买ID
     * @return 结果
     */
    @Override
    public int deleteMyGoodsBuyById(Integer id) {
        return myGoodsBuyMapper.deleteMyGoodsBuyById(id);
    }

    @Transactional
    @Override
    public synchronized Object exchange1(MyGoodsBuy myGoodsBuy1) {

        Integer goodsId = myGoodsBuy1.getGoodsId();
        MyGoods myGoods = myGoodsService.selectMyGoodsById(goodsId);
        if (myGoods == null){
            return AjaxResult.error("商品不存在");
        }

        Integer mid = SecurityUtils.getLoginUser().getWxUser().getMid();
        WxUser wxUser = wxUserService.selectWxUserById(mid);
        Integer isCombo = myGoods.getIsCombo();
        //积分
        Integer points = wxUser.getPoints();
        Integer goldCoin = wxUser.getGoldCoin();
        BigDecimal price = myGoods.getPrice();
        int i = price.intValue();
        String orderId ="";
        Map<String, String> map = new HashMap<>();
        MyGoodsBuy myGoodsBuy =new MyGoodsBuy();
        if (isCombo.equals(0)){
            myGoodsBuy.setIsCombo(0);
            if (points< i){
                //积分不够
                //Integer jinbi = myGoodsBuy1.getJinbi();
                Integer m =  i / 100;
                /*if (!jinbi.equals(m)){
                    return  new CustomException("核对金币有误");
                }*/


                if (goldCoin < m){
                    // 金币不够需要用钱支付
                    if (myGoodsBuy1.getRmb() == null){
                        throw new CustomException("需要支付的RMB为空");
                    }
                    Integer price1 = myGoodsBuy1.getRmb().intValue();
                    if (!price1.equals(m)){
                        throw new CustomException("核销的金额有误");
                    }

                    //需要用钱付了
                    WxOrder wxOrder = new WxOrder();
                    MyWxPayConfigUtil myWxPayConfigUtil = new MyWxPayConfigUtil();
                    //myWxPayConfigUtil.setAppId(WxConfig.APP_ID);
                    myWxPayConfigUtil.setTotalAmount(String.valueOf( new BigDecimal(m).multiply(new BigDecimal(100)).intValue()) );
                    orderId = String.valueOf(idWorker.nextId()) ;
                    Date date = new Date();
                    myWxPayConfigUtil.setOrderId(orderId);
                    myWxPayConfigUtil.setOpenId(wxUser.getOpenid());
                    myWxPayConfigUtil.setDate(date);
                    try {

                        wxOrder.setTotalPrice(new BigDecimal(m) );
                        wxOrder.setUserId(mid);
                        //0待支付,1已支付,2已退款,3关闭支付,4已删除"
                        wxOrder.setStatus(0);
                        wxOrder.setCreateTime(date);
                        wxOrder.setId(orderId);
                        wxOrder.setExpireTime(DateUtil.adjustDateByMinutes(date, 30, 1));
                        wxOrder.setType(8);//商城商品
                        wxOrder.setRemark(goodsId+"");//商品id
                        //wxOrder1.setTransactionId(wxOrder.getTransactionId());

                        map = PayUtil.test4(myWxPayConfigUtil);
                        if (map.get("returnCode").equals("000000")) {
                            wxOrder.setPrepayId(map.get("PrepayId"));// 预支付id
                            wxOrder.setOrderNo(map.get("orderNo"));// 国通交易订单号
                            wxOrderMapper.insertWxOrder(wxOrder);
                            map.put("orderId",orderId);
                            // 监听订单过期 修改订单状态
                            redisCache.setCacheObject("orderId:"+orderId,"abc",30, TimeUnit.MINUTES);
                            myGoodsBuy1.setIsPay(0);//待支付

                        } else {
                            throw new CustomException(map.get("message"), 400);
                        }

                    } catch (InterruptedException | IOException | ExecutionException e) {
                        e.printStackTrace();
                    }


                }else {
                    // 金币够付
                    Integer price1 = myGoodsBuy1.getJinbi();
                    if (price1 == null){
                        throw new CustomException("需要支付的金币为空");
                    }
                    if (!price1.equals(m)){
                        throw new CustomException("核销的金额有误");
                    }
                    //金币日志

                    Integer nowgoldCoin = goldCoin - m;
                    UserGoldLog userGoldLog = new UserGoldLog();
                    userGoldLog.setOldBalance(new BigDecimal(goldCoin) );
                    userGoldLog.setChangeBalance(new BigDecimal(m).negate() );
                    userGoldLog.setNewBalance(new BigDecimal(nowgoldCoin) );
                    userGoldLog.setType(7);//兑换商城商品，
                    userGoldLog.setCreated(new Date());
                    userGoldLog.setUserId(mid);
                    userGoldLog.setRemark( "购买商城商品(积分不够金币抵付)");//
                    userGoldLog.setFromSourceId(goodsId+"");//商品id
                    userGoldLogService.insertUserGoldLog(userGoldLog);

                    wxUser.setGoldCoin(nowgoldCoin);
                    wxUserService.updateWxUser(wxUser);

                    myGoodsBuy1.setIsPay(1);

                }

            }else {
                // 积分够的情况
                //积分日志
                Integer price1 = myGoodsBuy1.getJifen();
                if (price1 == null){
                    return  new CustomException("核对积分值为空");
                }
                if (price1.equals(i)){
                    return  new CustomException("核对积分有误");
                }
                UserPointLog userPointLog = new UserPointLog();
                userPointLog.setRemark("兑换商品(积分足够)");
                userPointLog.setOldPoint(points);
                userPointLog.setChangePoint( -i );
                userPointLog.setNewPoint(points - price1);
                userPointLog.setUserId(mid);
                userPointLog.setType(5);//兑换
                userPointLog.setCreated(new Date());
                userPointLogService.insertUserPointLog(userPointLog);

                myGoodsBuy1.setIsPay(0);
            }


        }else if (isCombo.equals(1)){
            //金币
            myGoodsBuy1.setIsCombo(1);
            if (goldCoin< i){
                //金币不够的情况 用钱付 补足
                if (myGoodsBuy1.getRmb() == null){
                    throw new CustomException("需要支付的RMB为空");
                }
                Integer price1 = myGoodsBuy1.getRmb().intValue();
                if (!price1.equals(i)){
                    throw new CustomException("核销的金额有误");
                }

                //需要用钱付了
                WxOrder wxOrder = new WxOrder();
                MyWxPayConfigUtil myWxPayConfigUtil = new MyWxPayConfigUtil();
                //myWxPayConfigUtil.setAppId(WxConfig.APP_ID);
                myWxPayConfigUtil.setTotalAmount(String.valueOf( new BigDecimal(i).multiply(new BigDecimal(100)).intValue()) );
                orderId = String.valueOf(idWorker.nextId()) ;
                Date date = new Date();
                myWxPayConfigUtil.setOrderId(orderId);
                myWxPayConfigUtil.setOpenId(wxUser.getOpenid());
                myWxPayConfigUtil.setDate(date);
                try {

                    wxOrder.setTotalPrice(new BigDecimal(i) );
                    wxOrder.setUserId(mid);
                    //0待支付,1已支付,2已退款,3关闭支付,4已删除"
                    wxOrder.setStatus(0);
                    wxOrder.setCreateTime(date);
                    wxOrder.setId(orderId);
                    wxOrder.setExpireTime(DateUtil.adjustDateByMinutes(date, 30, 1));
                    wxOrder.setType(8);//商城商品
                    wxOrder.setRemark(goodsId+"");//商品id
                    //wxOrder1.setTransactionId(wxOrder.getTransactionId());

                    map = PayUtil.test4(myWxPayConfigUtil);
                    if (map.get("returnCode").equals("000000")) {
                        wxOrder.setPrepayId(map.get("PrepayId"));// 预支付id
                        wxOrder.setOrderNo(map.get("orderNo"));// 国通交易订单号
                        wxOrderMapper.insertWxOrder(wxOrder);

                        map.put("orderId",orderId);
                        // 监听订单过期 修改订单状态
                        redisCache.setCacheObject("orderId:"+orderId,"abc",30, TimeUnit.MINUTES);
                        myGoodsBuy1.setIsPay(0);
                    } else {
                        throw new CustomException(map.get("message"), 400);
                    }


                } catch (InterruptedException | IOException | ExecutionException e) {
                    e.printStackTrace();
                }

            }else {

                //金币够
                // 金币够付
                Integer price1 = myGoodsBuy1.getJinbi();
                if (price1 == null){
                    throw new CustomException("需要支付的金币为空");
                }
                if (!price1.equals(i)){
                    throw new CustomException("核销的金额有误");
                }

                //金币日志
                Integer now = goldCoin - i;
                UserGoldLog userGoldLog = new UserGoldLog();
                userGoldLog.setRemark("购买商城商品");
                userGoldLog.setOldBalance(new BigDecimal(goldCoin) );
                userGoldLog.setChangeBalance(new BigDecimal(i).negate());
                userGoldLog.setNewBalance(new BigDecimal( now));
                userGoldLog.setUserId(mid);
                userGoldLog.setType(7);//兑换商品
                userGoldLog.setCreated(new Date());
                userGoldLogService.insertUserGoldLog(userGoldLog);

                wxUser.setGoldCoin(goldCoin - price.intValue());
                wxUserService.updateWxUser(wxUser);

                myGoodsBuy1.setIsPay(0);
            }


        }else if (isCombo.equals(2)){

            //金币和积分
            myGoodsBuy.setIsCombo(2);
            Integer jifen = myGoods.getJifen();
            Integer jinbi = myGoods.getJinbi();
            if (points < jifen){
                //积分不足的情况
                Integer n = jifen /100; // 积分兑换的金币
                n = n + jinbi;
                if (goldCoin < n){
                    // 金币不足 钱支付
                    //金币不够的情况
                    if (myGoodsBuy1.getRmb() == null){
                        throw new CustomException("需要支付的RMB为空");
                    }
                    Integer price1 = myGoodsBuy1.getRmb().intValue();
                    if (!price1.equals(n)){
                        throw new CustomException("核销的金额有误");
                    }

                    //需要用钱付了
                    WxOrder wxOrder = new WxOrder();
                    MyWxPayConfigUtil myWxPayConfigUtil = new MyWxPayConfigUtil();
                    //myWxPayConfigUtil.setAppId(WxConfig.APP_ID);
                    myWxPayConfigUtil.setTotalAmount(String.valueOf( new BigDecimal(i).multiply(new BigDecimal(100)).intValue()) );
                    orderId = String.valueOf(idWorker.nextId()) ;
                    Date date = new Date();
                    myWxPayConfigUtil.setOrderId(orderId);
                    myWxPayConfigUtil.setOpenId(wxUser.getOpenid());
                    myWxPayConfigUtil.setDate(date);
                    try {

                        wxOrder.setTotalPrice(new BigDecimal(i) );
                        wxOrder.setUserId(mid);
                        //0待支付,1已支付,2已退款,3关闭支付,4已删除"
                        wxOrder.setStatus(0);
                        wxOrder.setCreateTime(date);
                        wxOrder.setId(orderId);
                        wxOrder.setExpireTime(DateUtil.adjustDateByMinutes(date, 30, 1));
                        wxOrder.setType(8);//商城商品
                        wxOrder.setRemark(goodsId+"");//商品id
                        //wxOrder1.setTransactionId(wxOrder.getTransactionId());

                        map = PayUtil.test4(myWxPayConfigUtil);
                        if (map.get("returnCode").equals("000000")) {
                            wxOrder.setPrepayId(map.get("PrepayId"));// 预支付id
                            wxOrder.setOrderNo(map.get("orderNo"));// 国通交易订单号
                            wxOrderMapper.insertWxOrder(wxOrder);

                            map.put("orderId",orderId);
                            // 监听订单过期 修改订单状态
                            redisCache.setCacheObject("orderId:"+orderId,"abc",30, TimeUnit.MINUTES);

                            myGoodsBuy1.setIsPay(0);
                        } else {
                            throw new CustomException(map.get("message"), 400);
                        }

                        return map;
                    } catch (InterruptedException | IOException | ExecutionException e) {
                        e.printStackTrace();
                    }

                }else {
                    //金币足够
                    // 金币够付
                    Integer price1 = myGoodsBuy1.getJinbi();
                    if (price1 == null){
                        throw new CustomException("需要支付的金币为空");
                    }
                    if (!price1.equals(n)){
                        throw new CustomException("核销的金额有误");
                    }

                    //金币日志
                    Integer nowgolodCoin =  goldCoin - n;
                    UserGoldLog userGoldLog = new UserGoldLog();
                    userGoldLog.setRemark("购买商城商品(金币够,积分不够)");
                    userGoldLog.setOldBalance(new BigDecimal(goldCoin) );
                    userGoldLog.setChangeBalance(new BigDecimal(n).negate());
                    userGoldLog.setNewBalance(new BigDecimal( nowgolodCoin));
                    userGoldLog.setUserId(mid);
                    userGoldLog.setType(7);//兑换商品
                    userGoldLog.setCreated(new Date());
                    userGoldLogService.insertUserGoldLog(userGoldLog);

                    wxUser.setGoldCoin(nowgolodCoin);
                    wxUserService.updateWxUser(wxUser);

                }

            }else {
                //积分足够

            }



            //积分日志
            UserPointLog userPointLog = new UserPointLog();
            userPointLog.setRemark("兑换商品");
            userPointLog.setOldPoint(points);
            userPointLog.setChangePoint(jifen);
            userPointLog.setNewPoint(points - jifen);
            userPointLog.setUserId(mid);
            userPointLog.setType(5);//兑换
            userPointLog.setCreated(new Date());
            userPointLogService.insertUserPointLog(userPointLog);

            //金币日志
            UserGoldLog userGoldLog = new UserGoldLog();
            userGoldLog.setRemark("兑换商品");
            userGoldLog.setOldBalance(new BigDecimal(goldCoin) );
            userGoldLog.setChangeBalance(new BigDecimal(jinbi).negate());
            userGoldLog.setNewBalance(new BigDecimal( goldCoin - jinbi));
            userGoldLog.setUserId(mid);
            userGoldLog.setType(7);//兑换
            userGoldLog.setCreated(new Date());
            userGoldLogService.insertUserGoldLog(userGoldLog);

            wxUser.setGoldCoin(goldCoin - jinbi);
            wxUser.setPoints(points - jifen);
            wxUserService.updateWxUser(wxUser);

        }
        List<MyGoodsCat> myGoodsCats = myGoodsCatService.selectMyGoodsCatList(null);
        for (MyGoodsCat myGoodsCat : myGoodsCats) {
            if (myGoodsCat.getId().equals(myGoods.getGoodsCatId())) {
                myGoodsBuy1.setCat(myGoodsCat.getName());
            }
        }
        myGoodsBuy1.setUserId(mid);
        myGoodsBuy1.setCtime(new Date());
        myGoodsBuy1.setImg(myGoods.getImageId());//商品图
        myGoodsBuy1.setGoodsName(myGoods.getName());
        myGoodsBuy1.setGoodsId(goodsId);
        myGoodsBuy1.setPrice(myGoods.getPrice());
        myGoodsBuy1.setStatus(0);//待发货
        myGoodsBuy1.setOrderId(orderId);

        insertMyGoodsBuy(myGoodsBuy);
        return map;
    }

    @Override
    public int getMonthNum(Integer mid, Integer goodsId) {

        return myGoodsBuyMapper.getMonthNum(mid,goodsId);
    }

    @Override
    public int getYearNum(Integer mid, Integer goodsId) {
        return myGoodsBuyMapper.getYearNum(mid,goodsId);
    }
}
